<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TodoList 网页版</title>
    
    <!-- PWA Manifest -->
    <link rel="manifest" href="./manifest.json">
    
    <!-- Theme Color -->
    <meta name="theme-color" content="#3b82f6">
    <meta name="msapplication-TileColor" content="#3b82f6">
    
    <!-- iOS Meta Tags -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="TodoList">
    <link rel="apple-touch-icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 192 192'%3E%3Crect width='192' height='192' rx='36' fill='%233b82f6'/%3E%3Cpath d='M60 88l28 28 44-44' stroke='%23fff' stroke-width='16' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M60 60h72M60 132h72M60 96h16' stroke='%23fff' stroke-width='12' stroke-linecap='round'/%3E%3C/svg%3E">
    
    <!-- Favicon -->
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect width='100' height='100' rx='20' fill='%233b82f6'/%3E%3Cpath d='M30 45l15 15 25-25' stroke='%23fff' stroke-width='8' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M30 30h40M30 70h40M30 50h10' stroke='%23fff' stroke-width='6' stroke-linecap='round'/%3E%3C/svg%3E">
    
    <!-- Description -->
    <meta name="description" content="强大的任务管理和工作日记应用，支持离线使用，可安装到手机主屏幕">
    <meta name="keywords" content="todolist,任务管理,工作日记,待办事项,GTD">
    
    <script src="https://cdn.tailwindcss.com/3.3.3"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    
    <!-- Firebase SDK -->
    <script type="module">
        // Firebase配置将在这里注入
        window.firebaseConfig = null;
    </script>
    
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f8fafc;
            color: #1e293b;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .app-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        .header {
            background-color: white;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
            z-index: 10;
        }
        .content {
            flex: 1;
            overflow-y: auto;
            padding-bottom: 60px;
        }
        .content:has(.home-layout) {
            overflow: hidden;
            padding-bottom: 60px;
        }
        .tab-bar {
            background-color: white;
            box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
            height: 60px;
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            display: flex;
            z-index: 10;
        }
        .tab-item {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: #64748b;
            font-size: 12px;
        }
        .tab-item.active {
            color: #3b82f6;
        }
        .tab-item i {
            font-size: 22px;
            margin-bottom: 4px;
        }
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 20;
            display: none;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .modal-overlay.show {
            opacity: 1;
        }
        .modal-content {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background-color: white;
            border-radius: 16px 16px 0 0;
            padding: 20px;
            transform: translateY(100%);
            transition: transform 0.3s ease;
            z-index: 21;
        }
        .modal-content.show {
            transform: translateY(0);
        }
        .priority-high {
            border-left: 4px solid #ef4444;
        }
        .priority-medium {
            border-left: 4px solid #f59e0b;
        }
        .priority-low {
            border-left: 4px solid #10b981;
        }
        .chart-container {
            height: 300px;
            position: relative;
        }
        .task-completed {
            text-decoration: line-through;
            color: #94a3b8;
        }
        .task-item {
            cursor: move;
            transition: all 0.2s ease;
        }
        .task-item.dragging {
            opacity: 0.5;
            transform: scale(0.98);
        }
        .task-item.drag-over {
            border-top: 3px solid #3b82f6;
        }
        .drag-handle {
            cursor: grab;
            color: #cbd5e1;
            transition: color 0.2s;
        }
        .drag-handle:hover {
            color: #64748b;
        }
        .drag-handle:active {
            cursor: grabbing;
        }
        .calendar-tasks-container {
            margin-top: 20px;
            min-height: 200px;
            perspective: 1000px;
        }
        .fan-task {
            background: white;
            border-radius: 12px;
            padding: 12px;
            margin-bottom: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transform-origin: center top;
            opacity: 0;
            animation: fanIn 0.4s ease forwards;
        }
        @keyframes fanIn {
            0% {
                opacity: 0;
                transform: translateY(-20px) rotateX(-90deg) scale(0.8);
            }
            60% {
                transform: translateY(5px) rotateX(5deg) scale(1.02);
            }
            100% {
                opacity: 1;
                transform: translateY(0) rotateX(0) scale(1);
            }
        }
        .fan-task:nth-child(1) { animation-delay: 0s; }
        .fan-task:nth-child(2) { animation-delay: 0.08s; }
        .fan-task:nth-child(3) { animation-delay: 0.16s; }
        .fan-task:nth-child(4) { animation-delay: 0.24s; }
        .fan-task:nth-child(5) { animation-delay: 0.32s; }
        .fan-task:nth-child(6) { animation-delay: 0.40s; }
        .fan-task:nth-child(7) { animation-delay: 0.48s; }
        .fan-task:nth-child(8) { animation-delay: 0.56s; }
        .fan-task:nth-child(9) { animation-delay: 0.64s; }
        .fan-task:nth-child(10) { animation-delay: 0.72s; }
        .calendar-day-dot {
            width: 4px;
            height: 4px;
            background-color: #3b82f6;
            border-radius: 50%;
            position: absolute;
            bottom: 2px;
            left: 50%;
            transform: translateX(-50%);
        }
        .calendar-day {
            position: relative;
        }
        .stats-card {
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .stats-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        .stats-card:active {
            transform: translateY(-2px);
        }
        .task-list-item {
            background: white;
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 10px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            transition: all 0.2s ease;
        }
        .task-list-item:hover {
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
        }
        .notes-section {
            background: white;
            border-radius: 12px;
            padding: 16px;
            margin-top: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        .notes-textarea {
            width: 100%;
            min-height: 100px;
            max-height: 150px;
            padding: 12px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            line-height: 1.6;
            resize: none;
            transition: border-color 0.2s;
            font-family: inherit;
            overflow-y: auto;
        }
        .notes-textarea:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        .notes-textarea::placeholder {
            color: #94a3b8;
        }
        .notes-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }
        .save-indicator {
            font-size: 12px;
            color: #10b981;
            opacity: 0;
            transition: opacity 0.3s;
        }
        .save-indicator.show {
            opacity: 1;
        }
        .search-buttons {
            display: flex;
            gap: 12px;
            margin-top: 16px;
        }
        .search-btn {
            flex: 1;
            padding: 12px;
            border-radius: 8px;
            border: none;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .search-btn i {
            margin-right: 6px;
        }
        .search-btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .search-btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }
        .search-btn-secondary {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }
        .search-btn-secondary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(245, 87, 108, 0.4);
        }
        .data-buttons {
            display: flex;
            gap: 12px;
            margin-top: 12px;
        }
        .data-btn {
            flex: 1;
            padding: 10px;
            border-radius: 8px;
            border: 2px solid;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            background: white;
        }
        .data-btn i {
            margin-right: 6px;
        }
        .data-btn-export {
            border-color: #10b981;
            color: #10b981;
        }
        .data-btn-export:hover {
            background: #10b981;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
        }
        .data-btn-import {
            border-color: #f59e0b;
            color: #f59e0b;
        }
        .data-btn-import:hover {
            background: #f59e0b;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
        }
        .file-input-hidden {
            display: none;
        }
        .task-list-container {
            max-height: 480px;
            overflow-y: auto;
            padding-right: 4px;
        }
        .task-list-container::-webkit-scrollbar {
            width: 6px;
        }
        .task-list-container::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 3px;
        }
        .task-list-container::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 3px;
        }
        .task-list-container::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }
        .scroll-hint {
            text-align: center;
            padding: 8px;
            color: #94a3b8;
            font-size: 12px;
            border-top: 1px dashed #e2e8f0;
            margin-top: 8px;
            animation: fadeIn 0.5s ease;
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        .task-count-badge {
            display: inline-block;
            background: #eff6ff;
            color: #3b82f6;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            margin-left: 8px;
        }
        .sync-status {
            position: fixed;
            top: 50px;
            right: 10px;
            background: white;
            padding: 8px 12px;
            border-radius: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            font-size: 12px;
            z-index: 100;
            display: none;
            align-items: center;
            gap: 6px;
        }
        .sync-status.show {
            display: flex;
        }
        .sync-status.syncing {
            color: #3b82f6;
        }
        .sync-status.synced {
            color: #10b981;
        }
        .sync-status.error {
            color: #ef4444;
        }
        .sync-spinner {
            width: 14px;
            height: 14px;
            border: 2px solid #e5e7eb;
            border-top-color: #3b82f6;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .cloud-sync-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 16px;
            border-radius: 12px;
            margin-top: 16px;
        }
        .cloud-sync-card button {
            background: white;
            color: #667eea;
            border: none;
            padding: 8px 16px;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.2s;
        }
        .cloud-sync-card button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        .cloud-sync-card button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .firebase-setup-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
        .firebase-setup-content {
            background: white;
            padding: 24px;
            border-radius: 16px;
            max-width: 500px;
            max-height: 80vh;
            overflow-y: auto;
            margin: 20px;
        }
        .search-result-item {
            background: white;
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 10px;
            border-left: 4px solid #3b82f6;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            transition: all 0.2s ease;
        }
        .search-result-item:hover {
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
            transform: translateX(4px);
        }
        .search-result-date {
            display: inline-block;
            background: #eff6ff;
            color: #3b82f6;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 8px;
        }
        .search-highlight {
            background: #fef08a;
            padding: 2px 4px;
            border-radius: 2px;
            font-weight: 500;
        }
        .search-empty {
            text-align: center;
            padding: 40px 20px;
            color: #94a3b8;
        }
        .home-layout {
            display: flex;
            flex-direction: column;
            height: 100%;
            overflow: hidden;
        }
        .tasks-area {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
            padding-bottom: 0;
        }
        .notes-fixed {
            flex-shrink: 0;
            background: #f8fafc;
            border-top: 1px solid #e2e8f0;
            padding: 16px;
            max-height: 240px;
        }
        .notes-section {
            margin-top: 0;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <!-- 小程序风格标题栏 -->
        <div class="header py-4 px-4 text-center">
            <h1 class="text-xl font-bold">TodoList</h1>
        </div>

        <!-- 内容区域 -->
        <div class="content" id="contentArea">
            <!-- 首页内容将通过JavaScript动态加载 -->
        </div>

        <!-- 底部导航栏 -->
        <div class="tab-bar">
            <div class="tab-item active" data-tab="home">
                <i class="fas fa-home"></i>
                <span>首页</span>
            </div>
            <div class="tab-item" data-tab="calendar">
                <i class="fas fa-calendar-alt"></i>
                <span>日历</span>
            </div>
            <div class="tab-item" data-tab="stats">
                <i class="fas fa-chart-pie"></i>
                <span>统计</span>
            </div>
        </div>

        <!-- 添加任务模态框 -->
        <div class="modal-overlay" id="modalOverlay"></div>
        <div class="modal-content" id="modalContent">
            <h2 class="text-lg font-bold mb-4">添加新任务</h2>
            <form id="taskForm">
                <div class="mb-4">
                    <label for="taskName" class="block text-sm font-medium text-gray-700 mb-1">任务名称</label>
                    <input type="text" id="taskName" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                </div>
                <div class="mb-4">
                    <label for="taskDescription" class="block text-sm font-medium text-gray-700 mb-1">任务描述</label>
                    <textarea id="taskDescription" rows="2" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                </div>
                <div class="mb-4">
                    <label for="taskDueDate" class="block text-sm font-medium text-gray-700 mb-1">截止日期</label>
                    <input type="date" id="taskDueDate" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">优先级</label>
                    <div class="flex space-x-4">
                        <label class="inline-flex items-center">
                            <input type="radio" name="priority" value="high" class="form-radio text-red-500" checked>
                            <span class="ml-2">高</span>
                        </label>
                        <label class="inline-flex items-center">
                            <input type="radio" name="priority" value="medium" class="form-radio text-yellow-500">
                            <span class="ml-2">中</span>
                        </label>
                        <label class="inline-flex items-center">
                            <input type="radio" name="priority" value="low" class="form-radio text-green-500">
                            <span class="ml-2">低</span>
                        </label>
                    </div>
                </div>
                <button type="submit" class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 transition-colors">
                    <i class="fas fa-plus mr-2"></i>添加任务
                </button>
            </form>
        </div>

        <!-- 任务清单模态框 -->
        <div class="modal-overlay" id="taskListModalOverlay"></div>
        <div class="modal-content" id="taskListModalContent" style="max-height: 80vh; overflow-y: auto;">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-lg font-bold" id="taskListTitle">任务清单</h2>
                <button id="closeTaskListModal" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div id="taskListContent"></div>
        </div>

        <!-- 搜索模态框 -->
        <div class="modal-overlay" id="searchModalOverlay"></div>
        <div class="modal-content" id="searchModalContent" style="max-height: 80vh; overflow-y: auto;">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-lg font-bold" id="searchModalTitle">
                    <i class="fas fa-search mr-2 text-blue-500"></i>搜索
                </h2>
                <button id="closeSearchModal" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div class="mb-4">
                <div class="relative">
                    <input 
                        type="text" 
                        id="searchInput" 
                        class="w-full px-4 py-3 pr-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                        placeholder="输入关键词搜索..."
                    >
                    <i class="fas fa-search absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                </div>
            </div>
            <div id="searchResults"></div>
        </div>

        <!-- 云同步状态指示器 -->
        <div class="sync-status" id="syncStatus">
            <div class="sync-spinner"></div>
            <span id="syncStatusText">同步中...</span>
        </div>

        <!-- Firebase设置模态框 -->
        <div class="firebase-setup-modal" id="firebaseSetupModal">
            <div class="firebase-setup-content">
                <h2 class="text-xl font-bold mb-4">☁️ 配置云端同步</h2>
                <p class="text-sm text-gray-600 mb-4">
                    使用Firebase实现自动云端同步，让您的数据在所有设备间实时同步。
                </p>
                
                <div class="mb-4 p-3 bg-blue-50 rounded-lg text-sm">
                    <p class="font-medium text-blue-800 mb-2">📝 快速设置步骤：</p>
                    <ol class="text-blue-700 space-y-1 ml-4 list-decimal">
                        <li>访问 <a href="https://console.firebase.google.com" target="_blank" class="underline">Firebase控制台</a></li>
                        <li>创建新项目或选择现有项目</li>
                        <li>添加Web应用</li>
                        <li>复制配置信息</li>
                        <li>粘贴到下方输入框</li>
                    </ol>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Firebase配置（JSON格式）</label>
                    <textarea 
                        id="firebaseConfigInput" 
                        class="w-full px-3 py-2 border border-gray-300 rounded-md font-mono text-xs"
                        rows="10"
                        placeholder='{
  "apiKey": "YOUR_API_KEY",
  "authDomain": "your-project.firebaseapp.com",
  "projectId": "your-project",
  "storageBucket": "your-project.appspot.com",
  "messagingSenderId": "123456789",
  "appId": "YOUR_APP_ID"
}'
                    ></textarea>
                </div>

                <div class="flex gap-3">
                    <button id="saveFirebaseConfig" class="flex-1 bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700">
                        保存配置
                    </button>
                    <button id="cancelFirebaseSetup" class="flex-1 bg-gray-200 text-gray-700 py-2 px-4 rounded-lg hover:bg-gray-300">
                        取消
                    </button>
                </div>

                <div class="mt-4 text-xs text-gray-500">
                    <p>💡 提示：配置保存后需要登录Google账号来使用云同步功能。</p>
                    <p class="mt-1">🔒 您的数据将加密存储在Firebase云端，完全私密安全。</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化变量
            let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
            let currentDate = new Date();
            let selectedDate = new Date();
            let currentTab = 'home';
            let currentPeriod = 'week';
            let draggedElement = null;

            // DOM元素
            const contentArea = document.getElementById('contentArea');
            const tabItems = document.querySelectorAll('.tab-item');
            const modalOverlay = document.getElementById('modalOverlay');
            const modalContent = document.getElementById('modalContent');
            const taskForm = document.getElementById('taskForm');

            // 渲染当前标签页内容
            function renderCurrentTab() {
                switch(currentTab) {
                    case 'home':
                        renderHome();
                        break;
                    case 'calendar':
                        renderCalendarView();
                        break;
                    case 'stats':
                        renderStatsView();
                        break;
                }
            }

            // 拖拽事件处理函数
            function handleDragStart(e) {
                draggedElement = this;
                this.classList.add('dragging');
                e.dataTransfer.effectAllowed = 'move';
                e.dataTransfer.setData('text/html', this.innerHTML);
            }

            function handleDragEnd(e) {
                this.classList.remove('dragging');
                document.querySelectorAll('.task-item').forEach(item => {
                    item.classList.remove('drag-over');
                });
            }

            function handleDragOver(e) {
                if (e.preventDefault) {
                    e.preventDefault();
                }
                e.dataTransfer.dropEffect = 'move';
                
                if (draggedElement !== this) {
                    this.classList.add('drag-over');
                }
                
                return false;
            }

            function handleDragLeave(e) {
                this.classList.remove('drag-over');
            }

            function handleDrop(e) {
                if (e.stopPropagation) {
                    e.stopPropagation();
                }
                
                if (draggedElement !== this) {
                    // 获取拖拽元素和目标元素的任务ID
                    const draggedId = draggedElement.getAttribute('data-id');
                    const targetId = this.getAttribute('data-id');
                    
                    // 找到当前日期的任务列表
                    const todayTasks = tasks.filter(task => {
                        const taskDate = new Date(task.dueDate);
                        return taskDate.getFullYear() === selectedDate.getFullYear() && 
                               taskDate.getMonth() === selectedDate.getMonth() && 
                               taskDate.getDate() === selectedDate.getDate();
                    });
                    
                    // 找到拖拽和目标任务在数组中的索引
                    const draggedTaskIndex = tasks.findIndex(task => task.id === draggedId);
                    const targetTaskIndex = tasks.findIndex(task => task.id === targetId);
                    
                    // 重新排序：将拖拽的任务移动到目标位置
                    const draggedTask = tasks[draggedTaskIndex];
                    tasks.splice(draggedTaskIndex, 1);
                    const newTargetIndex = tasks.findIndex(task => task.id === targetId);
                    tasks.splice(newTargetIndex, 0, draggedTask);
                    
                    // 保存更新后的任务列表
                    saveTasks();
                    renderCurrentTab();
                }
                
                return false;
            }

            // 渲染首页
            function renderHome() {
                const todayTasks = tasks.filter(task => {
                    const taskDate = new Date(task.dueDate);
                    return taskDate.getFullYear() === selectedDate.getFullYear() && 
                           taskDate.getMonth() === selectedDate.getMonth() && 
                           taskDate.getDate() === selectedDate.getDate();
                });

                // 格式化日期标题
                const dateTitle = `${selectedDate.getMonth() + 1}月${selectedDate.getDate()}日任务`;

                let html = `
                    <div class="home-layout">
                        <div class="tasks-area">
                            <div class="flex justify-between items-center mb-4">
                                <h2 class="text-lg font-bold">${dateTitle}</h2>
                                <button id="addTaskBtn" class="bg-blue-500 text-white rounded-full w-10 h-10 flex items-center justify-center">
                                    <i class="fas fa-plus"></i>
                                </button>
                            </div>
                `;

                if (todayTasks.length === 0) {
                    html += `
                        <div class="text-center py-8 text-gray-500">
                            <i class="fas fa-tasks text-4xl mb-2"></i>
                            <p>该日期没有任务</p>
                        </div>
                    `;
                } else {
                    todayTasks.forEach(task => {
                        const dueDate = new Date(task.dueDate);
                        const formattedDate = `${dueDate.getFullYear()}/${(dueDate.getMonth() + 1).toString().padStart(2, '0')}/${dueDate.getDate().toString().padStart(2, '0')}`;
                        
                        html += `
                            <div class="task-item bg-white rounded-lg p-3 mb-3 ${task.completed ? 'bg-gray-50' : ''} priority-${task.priority}" draggable="true" data-id="${task.id}">
                                <div class="flex justify-between items-start mb-1">
                                    <div class="flex items-center flex-1">
                                        <i class="fas fa-grip-vertical drag-handle mr-2"></i>
                                        <h3 class="font-medium ${task.completed ? 'task-completed' : ''}">${task.name}</h3>
                                    </div>
                                    <div class="flex space-x-2">
                                        <button class="text-gray-400 hover:text-gray-600 task-toggle" data-id="${task.id}">
                                            <i class="fas fa-${task.completed ? 'check-circle' : 'circle'}"></i>
                                        </button>
                                        <button class="text-gray-400 hover:text-gray-600 task-delete" data-id="${task.id}">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                ${task.description ? `<p class="text-sm text-gray-600 mb-2 ml-6 ${task.completed ? 'task-completed' : ''}">${task.description}</p>` : ''}
                                <div class="flex justify-between items-center ml-6">
                                    <span class="text-xs text-gray-500">截止日期: ${formattedDate}</span>
                                    <span class="text-xs ${task.priority === 'high' ? 'text-red-500' : task.priority === 'medium' ? 'text-yellow-500' : 'text-green-500'}">
                                        ${task.priority === 'high' ? '高优先级' : task.priority === 'medium' ? '中优先级' : '低优先级'}
                                    </span>
                                </div>
                            </div>
                        `;
                    });
                }

                // 关闭任务区域
                html += `</div>`;

                // 添加固定的工作日记区域
                html += `
                        <div class="notes-fixed">
                            <div class="notes-section">
                                <div class="notes-header">
                                    <h3 class="text-base font-bold text-gray-700 flex items-center">
                                        <i class="fas fa-pencil-alt mr-2 text-purple-500"></i>
                                        工作日记
                                    </h3>
                                    <span class="save-indicator" id="saveIndicator">
                                        <i class="fas fa-check-circle mr-1"></i>已保存
                                    </span>
                                </div>
                                <textarea 
                                    class="notes-textarea" 
                                    id="dailyNotes" 
                                    placeholder="在这里记录今天的工作心得、想法、总结...&#10;&#10;支持多行输入，内容会自动保存。"
                                ></textarea>
                                <div class="text-xs text-gray-400 mt-2">
                                    <i class="fas fa-info-circle mr-1"></i>内容会自动保存，每个日期都有独立的备注
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                contentArea.innerHTML = html;

                // 添加事件监听器
                document.getElementById('addTaskBtn').addEventListener('click', openModal);
                document.querySelectorAll('.task-toggle').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const taskId = this.getAttribute('data-id');
                        toggleTaskCompletion(taskId);
                    });
                });
                document.querySelectorAll('.task-delete').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const taskId = this.getAttribute('data-id');
                        deleteTask(taskId);
                    });
                });
                
                // 添加拖拽事件监听器
                const taskItems = document.querySelectorAll('.task-item');
                taskItems.forEach(item => {
                    item.addEventListener('dragstart', handleDragStart);
                    item.addEventListener('dragend', handleDragEnd);
                    item.addEventListener('dragover', handleDragOver);
                    item.addEventListener('drop', handleDrop);
                    item.addEventListener('dragleave', handleDragLeave);
                });
                
                // 加载并设置当天的备注
                const dailyNotesTextarea = document.getElementById('dailyNotes');
                const savedNote = loadDailyNote(selectedDate);
                if (savedNote) {
                    dailyNotesTextarea.value = savedNote;
                }
                
                // 添加备注自动保存功能
                let saveTimeout;
                dailyNotesTextarea.addEventListener('input', function() {
                    clearTimeout(saveTimeout);
                    saveTimeout = setTimeout(() => {
                        saveDailyNote(selectedDate, this.value);
                        showSaveIndicator();
                    }, 1000); // 1秒后自动保存
                });
            }

            // 保存每日备注
            function saveDailyNote(date, note) {
                const dateKey = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
                let dailyNotes = JSON.parse(localStorage.getItem('dailyNotes')) || {};
                dailyNotes[dateKey] = note;
                localStorage.setItem('dailyNotes', JSON.stringify(dailyNotes));
            }
            
            // 加载每日备注
            function loadDailyNote(date) {
                const dateKey = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
                let dailyNotes = JSON.parse(localStorage.getItem('dailyNotes')) || {};
                return dailyNotes[dateKey] || '';
            }
            
            // 显示保存指示器
            function showSaveIndicator() {
                const indicator = document.getElementById('saveIndicator');
                if (indicator) {
                    indicator.classList.add('show');
                    setTimeout(() => {
                        indicator.classList.remove('show');
                    }, 2000); // 2秒后隐藏
                }
            }

            // 渲染日历视图
            function renderCalendarView() {
                const year = currentDate.getFullYear();
                const month = currentDate.getMonth();
                const firstDay = new Date(year, month, 1).getDay();
                const daysInMonth = new Date(year, month + 1, 0).getDate();
                
                let html = `
                    <div class="p-4">
                        <div class="flex justify-between items-center mb-4">
                            <h2 class="text-lg font-bold">${year}年${month + 1}月</h2>
                            <div class="flex space-x-2">
                                <button id="prevMonthBtn" class="bg-gray-200 rounded-full w-8 h-8 flex items-center justify-center">
                                    <i class="fas fa-chevron-left"></i>
                                </button>
                                <button id="nextMonthBtn" class="bg-gray-200 rounded-full w-8 h-8 flex items-center justify-center">
                                    <i class="fas fa-chevron-right"></i>
                                </button>
                            </div>
                        </div>
                        <div class="grid grid-cols-7 gap-1 mb-2">
                            <div class="text-center text-sm font-medium text-gray-500">日</div>
                            <div class="text-center text-sm font-medium text-gray-500">一</div>
                            <div class="text-center text-sm font-medium text-gray-500">二</div>
                            <div class="text-center text-sm font-medium text-gray-500">三</div>
                            <div class="text-center text-sm font-medium text-gray-500">四</div>
                            <div class="text-center text-sm font-medium text-gray-500">五</div>
                            <div class="text-center text-sm font-medium text-gray-500">六</div>
                        </div>
                        <div class="grid grid-cols-7 gap-1">
                `;
                
                // 上个月的最后几天
                for (let i = 0; i < firstDay; i++) {
                    html += `<div class="text-center py-2 text-gray-400"></div>`;
                }
                
                // 当前月的天数
                for (let i = 1; i <= daysInMonth; i++) {
                    const date = new Date(year, month, i);
                    const hasTasks = tasks.some(task => {
                        const taskDate = new Date(task.dueDate);
                        return taskDate.getFullYear() === date.getFullYear() && 
                               taskDate.getMonth() === date.getMonth() && 
                               taskDate.getDate() === date.getDate();
                    });
                    
                    const isToday = date.getDate() === new Date().getDate() && 
                                    date.getMonth() === new Date().getMonth() && 
                                    date.getFullYear() === new Date().getFullYear();
                    
                    const isSelected = date.getDate() === selectedDate.getDate() && 
                                      date.getMonth() === selectedDate.getMonth() && 
                                      date.getFullYear() === selectedDate.getFullYear();
                    
                    html += `
                        <div class="calendar-day text-center py-2 rounded-full cursor-pointer 
                            ${isToday ? 'bg-blue-100' : ''} 
                            ${isSelected ? 'bg-blue-500 text-white' : ''}
                            ${hasTasks ? 'font-bold' : ''}"
                            data-date="${date.toISOString()}"
                            data-has-tasks="${hasTasks}">
                            ${i}
                            ${hasTasks ? '<div class="calendar-day-dot"></div>' : ''}
                        </div>
                    `;
                }
                
                html += `</div>`;
                
                // 添加任务展示区域
                html += `
                    <div class="calendar-tasks-container" id="calendarTasksContainer">
                        <div id="selectedDateTasks"></div>
                    </div>
                </div>`;
                contentArea.innerHTML = html;
                
                // 添加事件监听器
                document.getElementById('prevMonthBtn').addEventListener('click', () => {
                    currentDate.setMonth(currentDate.getMonth() - 1);
                    renderCalendarView();
                });
                
                document.getElementById('nextMonthBtn').addEventListener('click', () => {
                    currentDate.setMonth(currentDate.getMonth() + 1);
                    renderCalendarView();
                });
                
                document.querySelectorAll('[data-date]').forEach(day => {
                    day.addEventListener('click', function() {
                        selectedDate = new Date(this.getAttribute('data-date'));
                        const hasTasks = this.getAttribute('data-has-tasks') === 'true';
                        
                        // 更新选中状态
                        document.querySelectorAll('.calendar-day').forEach(d => {
                            d.classList.remove('bg-blue-500', 'text-white');
                        });
                        this.classList.add('bg-blue-500', 'text-white');
                        
                        // 如果有任务，显示任务
                        if (hasTasks) {
                            showDateTasks(selectedDate);
                        } else {
                            document.getElementById('selectedDateTasks').innerHTML = `
                                <div class="text-center py-8 text-gray-400">
                                    <i class="fas fa-calendar-check text-3xl mb-2"></i>
                                    <p>该日期没有任务</p>
                                </div>
                            `;
                        }
                    });
                });
                
                // 如果当前选中日期有任务，自动显示
                const selectedDayElement = document.querySelector(`[data-date="${selectedDate.toISOString()}"]`);
                if (selectedDayElement && selectedDayElement.getAttribute('data-has-tasks') === 'true') {
                    showDateTasks(selectedDate);
                }
            }
            
            // 显示指定日期的任务（扇面展开）
            function showDateTasks(date) {
                const dateTasks = tasks.filter(task => {
                    const taskDate = new Date(task.dueDate);
                    return taskDate.getFullYear() === date.getFullYear() && 
                           taskDate.getMonth() === date.getMonth() && 
                           taskDate.getDate() === date.getDate();
                });
                
                if (dateTasks.length === 0) {
                    document.getElementById('selectedDateTasks').innerHTML = '';
                    return;
                }
                
                const dateStr = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
                let html = `
                    <div class="mb-3">
                        <h3 class="text-base font-bold text-gray-700 flex items-center">
                            <i class="fas fa-calendar-day mr-2 text-blue-500"></i>
                            ${dateStr} 的任务 (${dateTasks.length})
                        </h3>
                    </div>
                `;
                
                dateTasks.forEach((task, index) => {
                    html += `
                        <div class="fan-task priority-${task.priority}">
                            <div class="flex justify-between items-start mb-2">
                                <div class="flex items-center flex-1">
                                    <i class="fas fa-${task.completed ? 'check-circle text-green-500' : 'circle text-gray-400'} mr-2"></i>
                                    <h4 class="font-medium ${task.completed ? 'task-completed' : ''}">${task.name}</h4>
                                </div>
                                <span class="text-xs px-2 py-1 rounded ${
                                    task.priority === 'high' ? 'bg-red-100 text-red-600' : 
                                    task.priority === 'medium' ? 'bg-yellow-100 text-yellow-600' : 
                                    'bg-green-100 text-green-600'
                                }">
                                    ${task.priority === 'high' ? '高' : task.priority === 'medium' ? '中' : '低'}
                                </span>
                            </div>
                            ${task.description ? `
                                <p class="text-sm text-gray-600 ml-6 mb-2 ${task.completed ? 'task-completed' : ''}">${task.description}</p>
                            ` : ''}
                            <div class="flex justify-between items-center ml-6 text-xs text-gray-500">
                                <span><i class="fas fa-clock mr-1"></i>创建于 ${new Date(task.createdAt).toLocaleDateString()}</span>
                            </div>
                        </div>
                    `;
                });
                
                document.getElementById('selectedDateTasks').innerHTML = html;
            }

            // 渲染统计视图
            function renderStatsView() {
                const now = new Date();
                let startDate, endDate;
                
                switch (currentPeriod) {
                    case 'week':
                        const weekStart = new Date(now);
                        weekStart.setDate(now.getDate() - now.getDay());
                        startDate = new Date(weekStart.getFullYear(), weekStart.getMonth(), weekStart.getDate());
                        endDate = new Date(startDate);
                        endDate.setDate(startDate.getDate() + 6);
                        break;
                    case 'month':
                        startDate = new Date(now.getFullYear(), now.getMonth(), 1);
                        endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);
                        break;
                    case 'quarter':
                        const quarter = Math.floor(now.getMonth() / 3);
                        startDate = new Date(now.getFullYear(), quarter * 3, 1);
                        endDate = new Date(now.getFullYear(), quarter * 3 + 3, 0);
                        break;
                    case 'year':
                        startDate = new Date(now.getFullYear(), 0, 1);
                        endDate = new Date(now.getFullYear(), 11, 31);
                        break;
                }
                
                const filteredTasks = tasks.filter(task => {
                    const taskDate = new Date(task.dueDate);
                    return taskDate >= startDate && taskDate <= endDate;
                });
                
                const completedCount = filteredTasks.filter(task => task.completed).length;
                const pendingCount = filteredTasks.filter(task => !task.completed).length;
                
                let html = `
                    <div class="p-4">
                        <h2 class="text-lg font-bold mb-4">任务统计</h2>
                        <div class="flex justify-center mb-4">
                            <div class="inline-flex rounded-md shadow-sm" role="group">
                                <button type="button" class="px-4 py-2 text-sm font-medium ${currentPeriod === 'week' ? 'bg-blue-50 text-blue-600' : 'bg-white text-gray-700'} border border-gray-200 rounded-l-lg time-filter" data-period="week">
                                    本周
                                </button>
                                <button type="button" class="px-4 py-2 text-sm font-medium ${currentPeriod === 'month' ? 'bg-blue-50 text-blue-600' : 'bg-white text-gray-700'} border-t border-b border-gray-200 time-filter" data-period="month">
                                    本月
                                </button>
                                <button type="button" class="px-4 py-2 text-sm font-medium ${currentPeriod === 'quarter' ? 'bg-blue-50 text-blue-600' : 'bg-white text-gray-700'} border-t border-b border-gray-200 time-filter" data-period="quarter">
                                    本季
                                </button>
                                <button type="button" class="px-4 py-2 text-sm font-medium ${currentPeriod === 'year' ? 'bg-blue-50 text-blue-600' : 'bg-white text-gray-700'} border border-gray-200 rounded-r-lg time-filter" data-period="year">
                                    本年
                                </button>
                            </div>
                        </div>
                        <div class="chart-container mb-4">
                            <canvas id="taskStatsChart"></canvas>
                        </div>
                        <div class="grid grid-cols-2 gap-4">
                            <div class="stats-card bg-blue-50 p-3 rounded-lg" data-task-type="completed">
                                <p class="text-sm text-blue-600 font-medium flex items-center">
                                    <i class="fas fa-check-circle mr-2"></i>已完成任务
                                </p>
                                <p class="text-2xl font-bold text-blue-800">${completedCount}</p>
                                <p class="text-xs text-blue-500 mt-1">点击查看详情 <i class="fas fa-arrow-right ml-1"></i></p>
                            </div>
                            <div class="stats-card bg-green-50 p-3 rounded-lg" data-task-type="pending">
                                <p class="text-sm text-green-600 font-medium flex items-center">
                                    <i class="fas fa-clock mr-2"></i>未完成任务
                                </p>
                                <p class="text-2xl font-bold text-green-800">${pendingCount}</p>
                                <p class="text-xs text-green-500 mt-1">点击查看详情 <i class="fas fa-arrow-right ml-1"></i></p>
                            </div>
                        </div>
                        <div class="search-buttons">
                            <button class="search-btn search-btn-primary" id="searchTasksBtn">
                                <i class="fas fa-tasks"></i>搜索任务
                            </button>
                            <button class="search-btn search-btn-secondary" id="searchNotesBtn">
                                <i class="fas fa-book"></i>搜索工作日记
                            </button>
                        </div>
                        <div class="data-buttons">
                            <button class="data-btn data-btn-export" id="exportDataBtn">
                                <i class="fas fa-download"></i>导出数据
                            </button>
                            <button class="data-btn data-btn-import" id="importDataBtn">
                                <i class="fas fa-upload"></i>导入数据
                            </button>
                        </div>
                        <input type="file" id="importFileInput" class="file-input-hidden" accept=".json">
                        
                        <!-- 云同步卡片 -->
                        <div class="cloud-sync-card" id="cloudSyncCard">
                            <div class="flex items-center justify-between mb-3">
                                <div>
                                    <h3 class="font-bold text-lg mb-1">
                                        <i class="fas fa-cloud mr-2"></i>云端同步
                                    </h3>
                                    <p class="text-sm opacity-90" id="cloudSyncStatus">
                                        未配置
                                    </p>
                                </div>
                                <i class="fas fa-sync-alt text-2xl"></i>
                            </div>
                            <p class="text-sm opacity-90 mb-3">
                                配置Firebase云同步，实现多设备自动同步，数据永不丢失。
                            </p>
                            <button id="setupCloudSyncBtn">
                                <i class="fas fa-cog mr-2"></i>配置云同步
                            </button>
                        </div>
                    </div>
                `;
                
                contentArea.innerHTML = html;
                
                // 渲染图表
                const ctx = document.getElementById('taskStatsChart').getContext('2d');
                new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: ['已完成', '未完成'],
                        datasets: [{
                            data: [completedCount, pendingCount],
                            backgroundColor: ['#3b82f6', '#10b981'],
                            borderWidth: 0
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        },
                        cutout: '70%'
                    }
                });
                
                // 添加事件监听器
                document.querySelectorAll('.time-filter').forEach(btn => {
                    btn.addEventListener('click', function() {
                        currentPeriod = this.getAttribute('data-period');
                        renderStatsView();
                    });
                });
                
                // 添加统计卡片点击事件
                document.querySelectorAll('.stats-card').forEach(card => {
                    card.addEventListener('click', function() {
                        const taskType = this.getAttribute('data-task-type');
                        showTaskListModal(taskType, filteredTasks);
                    });
                });
                
                // 添加搜索按钮事件
                document.getElementById('searchTasksBtn').addEventListener('click', () => {
                    openSearchModal('tasks');
                });
                document.getElementById('searchNotesBtn').addEventListener('click', () => {
                    openSearchModal('notes');
                });
                
                // 添加导出/导入按钮事件
                document.getElementById('exportDataBtn').addEventListener('click', exportData);
                document.getElementById('importDataBtn').addEventListener('click', () => {
                    document.getElementById('importFileInput').click();
                });
                document.getElementById('importFileInput').addEventListener('change', handleImportFile);
            }
            
            // 导出数据
            function exportData(silent = false) {
                try {
                    const data = {
                        version: '1.0',
                        exportDate: new Date().toISOString(),
                        tasks: tasks,
                        dailyNotes: JSON.parse(localStorage.getItem('dailyNotes')) || {}
                    };
                    
                    const dataStr = JSON.stringify(data, null, 2);
                    const blob = new Blob([dataStr], { type: 'application/json' });
                    const url = URL.createObjectURL(blob);
                    
                    const a = document.createElement('a');
                    a.href = url;
                    const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
                    a.download = `todolist-backup-${timestamp}.json`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    
                    // 记录最后备份时间
                    localStorage.setItem('lastBackupTime', new Date().toISOString());
                    
                    if (!silent) {
                        alert('✅ 数据导出成功！\n\n文件已保存到下载文件夹。');
                    }
                    
                    return true;
                } catch (error) {
                    console.error('导出失败:', error);
                    if (!silent) {
                        alert('❌ 导出失败：' + error.message);
                    }
                    return false;
                }
            }
            
            // 自动备份提醒
            function checkAutoBackup() {
                const lastBackup = localStorage.getItem('lastBackupTime');
                const autoBackupEnabled = localStorage.getItem('autoBackupEnabled') !== 'false';
                
                if (!autoBackupEnabled) return;
                
                const now = new Date();
                if (!lastBackup) {
                    // 首次使用，提示设置自动备份
                    setTimeout(() => {
                        if (confirm('💡 数据同步提示\n\n建议定期备份数据，是否启用自动备份提醒？\n\n启用后将在每次启动时检查并提醒备份（3天一次）')) {
                            localStorage.setItem('autoBackupEnabled', 'true');
                            localStorage.setItem('lastBackupTime', now.toISOString());
                        } else {
                            localStorage.setItem('autoBackupEnabled', 'false');
                        }
                    }, 3000);
                    return;
                }
                
                const lastBackupDate = new Date(lastBackup);
                const daysSinceBackup = Math.floor((now - lastBackupDate) / (1000 * 60 * 60 * 24));
                
                // 3天未备份则提醒
                if (daysSinceBackup >= 3) {
                    setTimeout(() => {
                        if (confirm(`📅 备份提醒\n\n距离上次备份已经 ${daysSinceBackup} 天了。\n\n是否现在备份数据？\n\n（备份文件可用于在其他设备上同步）`)) {
                            exportData(false);
                        } else {
                            // 延后提醒
                            localStorage.setItem('lastBackupTime', now.toISOString());
                        }
                    }, 2000);
                }
            }
            
            // 处理导入文件
            function handleImportFile(event) {
                const file = event.target.files[0];
                if (!file) return;
                
                if (!file.name.endsWith('.json')) {
                    alert('❌ 请选择JSON格式的备份文件');
                    return;
                }
                
                const reader = new FileReader();
                reader.onload = (e) => {
                    try {
                        const data = JSON.parse(e.target.result);
                        
                        // 验证数据格式
                        if (!data.tasks || !data.dailyNotes) {
                            throw new Error('备份文件格式不正确');
                        }
                        
                        // 显示确认对话框
                        const taskCount = data.tasks.length;
                        const noteCount = Object.keys(data.dailyNotes).length;
                        const exportDate = data.exportDate ? new Date(data.exportDate).toLocaleString('zh-CN') : '未知';
                        
                        const confirmed = confirm(
                            `📂 导入数据确认\n\n` +
                            `备份时间: ${exportDate}\n` +
                            `任务数量: ${taskCount} 个\n` +
                            `日记数量: ${noteCount} 条\n\n` +
                            `⚠️ 警告：导入将覆盖当前所有数据！\n` +
                            `当前数据：\n` +
                            `- 任务: ${tasks.length} 个\n` +
                            `- 日记: ${Object.keys(JSON.parse(localStorage.getItem('dailyNotes')) || {}).length} 条\n\n` +
                            `确定要导入吗？`
                        );
                        
                        if (confirmed) {
                            importData(data);
                        }
                    } catch (error) {
                        console.error('导入失败:', error);
                        alert('❌ 导入失败：' + error.message + '\n\n请确保选择的是有效的TodoList备份文件。');
                    }
                };
                reader.readAsText(file);
                
                // 重置文件输入，允许重复选择同一文件
                event.target.value = '';
            }
            
            // 导入数据
            function importData(data) {
                try {
                    // 保存数据到localStorage
                    localStorage.setItem('tasks', JSON.stringify(data.tasks));
                    localStorage.setItem('dailyNotes', JSON.stringify(data.dailyNotes));
                    
                    // 显示成功消息
                    alert('✅ 数据导入成功！\n\n页面即将刷新以加载新数据。');
                    
                    // 刷新页面
                    location.reload();
                } catch (error) {
                    console.error('导入失败:', error);
                    alert('❌ 导入失败：' + error.message);
                }
            }
            
            // 打开搜索模态框
            function openSearchModal(searchType) {
                const searchModalOverlay = document.getElementById('searchModalOverlay');
                const searchModalContent = document.getElementById('searchModalContent');
                const searchModalTitle = document.getElementById('searchModalTitle');
                const searchInput = document.getElementById('searchInput');
                const searchResults = document.getElementById('searchResults');
                
                // 设置标题
                if (searchType === 'tasks') {
                    searchModalTitle.innerHTML = '<i class="fas fa-tasks mr-2 text-blue-500"></i>搜索任务';
                    searchInput.placeholder = '输入任务名称或描述进行搜索...';
                } else {
                    searchModalTitle.innerHTML = '<i class="fas fa-book mr-2 text-pink-500"></i>搜索工作日记';
                    searchInput.placeholder = '输入关键词搜索工作日记...';
                }
                
                // 清空搜索框和结果
                searchInput.value = '';
                searchResults.innerHTML = `
                    <div class="search-empty">
                        <i class="fas fa-search text-5xl mb-3"></i>
                        <p>请输入关键词开始搜索</p>
                    </div>
                `;
                
                // 显示模态框
                searchModalOverlay.style.display = 'block';
                searchModalContent.style.display = 'block';
                setTimeout(() => {
                    searchModalOverlay.classList.add('show');
                    searchModalContent.classList.add('show');
                    searchInput.focus();
                }, 10);
                
                // 绑定搜索事件
                searchInput.oninput = function() {
                    if (searchType === 'tasks') {
                        searchTasks(this.value);
                    } else {
                        searchNotes(this.value);
                    }
                };
            }
            
            // 关闭搜索模态框
            function closeSearchModal() {
                const searchModalOverlay = document.getElementById('searchModalOverlay');
                const searchModalContent = document.getElementById('searchModalContent');
                
                searchModalOverlay.classList.remove('show');
                searchModalContent.classList.remove('show');
                setTimeout(() => {
                    searchModalOverlay.style.display = 'none';
                    searchModalContent.style.display = 'none';
                }, 300);
            }
            
            // 搜索任务
            function searchTasks(keyword) {
                const searchResults = document.getElementById('searchResults');
                
                if (!keyword.trim()) {
                    searchResults.innerHTML = `
                        <div class="search-empty">
                            <i class="fas fa-search text-5xl mb-3"></i>
                            <p>请输入关键词开始搜索</p>
                        </div>
                    `;
                    return;
                }
                
                // 搜索任务
                const results = tasks.filter(task => {
                    return task.name.toLowerCase().includes(keyword.toLowerCase()) || 
                           (task.description && task.description.toLowerCase().includes(keyword.toLowerCase()));
                });
                
                if (results.length === 0) {
                    searchResults.innerHTML = `
                        <div class="search-empty">
                            <i class="fas fa-inbox text-5xl mb-3"></i>
                            <p>未找到匹配的任务</p>
                            <p class="text-xs mt-2">尝试使用不同的关键词</p>
                        </div>
                    `;
                    return;
                }
                
                // 高亮关键词
                function highlightText(text, keyword) {
                    if (!text) return '';
                    const regex = new RegExp(`(${keyword})`, 'gi');
                    return text.replace(regex, '<span class="search-highlight">$1</span>');
                }
                
                let html = `<div class="mb-2 text-sm text-gray-600">找到 ${results.length} 个匹配的任务</div>`;
                results.forEach(task => {
                    const dueDate = new Date(task.dueDate);
                    const formattedDate = `${dueDate.getFullYear()}年${dueDate.getMonth() + 1}月${dueDate.getDate()}日`;
                    
                    html += `
                        <div class="search-result-item">
                            <span class="search-result-date">
                                <i class="fas fa-calendar mr-1"></i>${formattedDate}
                            </span>
                            <div class="flex items-start mb-2">
                                <i class="fas fa-${task.completed ? 'check-circle text-green-500' : 'circle text-gray-400'} mr-2 mt-1"></i>
                                <div class="flex-1">
                                    <h4 class="font-medium text-gray-800 ${task.completed ? 'task-completed' : ''}">${highlightText(task.name, keyword)}</h4>
                                    ${task.description ? `<p class="text-sm text-gray-600 mt-1">${highlightText(task.description, keyword)}</p>` : ''}
                                </div>
                                <span class="text-xs px-2 py-1 rounded ml-2 ${
                                    task.priority === 'high' ? 'bg-red-100 text-red-600' : 
                                    task.priority === 'medium' ? 'bg-yellow-100 text-yellow-600' : 
                                    'bg-green-100 text-green-600'
                                }">
                                    ${task.priority === 'high' ? '高' : task.priority === 'medium' ? '中' : '低'}
                                </span>
                            </div>
                            ${task.completed ? '<div class="text-xs text-green-600"><i class="fas fa-check mr-1"></i>已完成</div>' : ''}
                        </div>
                    `;
                });
                
                searchResults.innerHTML = html;
            }
            
            // 搜索工作日记
            function searchNotes(keyword) {
                const searchResults = document.getElementById('searchResults');
                
                if (!keyword.trim()) {
                    searchResults.innerHTML = `
                        <div class="search-empty">
                            <i class="fas fa-search text-5xl mb-3"></i>
                            <p>请输入关键词开始搜索</p>
                        </div>
                    `;
                    return;
                }
                
                // 加载所有日记
                const dailyNotes = JSON.parse(localStorage.getItem('dailyNotes')) || {};
                const results = [];
                
                for (const dateKey in dailyNotes) {
                    const note = dailyNotes[dateKey];
                    if (note.toLowerCase().includes(keyword.toLowerCase())) {
                        results.push({ dateKey, note });
                    }
                }
                
                if (results.length === 0) {
                    searchResults.innerHTML = `
                        <div class="search-empty">
                            <i class="fas fa-inbox text-5xl mb-3"></i>
                            <p>未找到匹配的工作日记</p>
                            <p class="text-xs mt-2">尝试使用不同的关键词</p>
                        </div>
                    `;
                    return;
                }
                
                // 高亮关键词
                function highlightText(text, keyword) {
                    if (!text) return '';
                    const regex = new RegExp(`(${keyword})`, 'gi');
                    return text.replace(regex, '<span class="search-highlight">$1</span>');
                }
                
                // 截取上下文
                function getContext(text, keyword, contextLength = 100) {
                    const index = text.toLowerCase().indexOf(keyword.toLowerCase());
                    if (index === -1) return text.substring(0, contextLength) + '...';
                    
                    const start = Math.max(0, index - contextLength / 2);
                    const end = Math.min(text.length, index + keyword.length + contextLength / 2);
                    
                    let context = text.substring(start, end);
                    if (start > 0) context = '...' + context;
                    if (end < text.length) context = context + '...';
                    
                    return context;
                }
                
                let html = `<div class="mb-2 text-sm text-gray-600">找到 ${results.length} 条匹配的工作日记</div>`;
                results.forEach(({ dateKey, note }) => {
                    const [year, month, day] = dateKey.split('-');
                    const formattedDate = `${year}年${month}月${day}日`;
                    const context = getContext(note, keyword, 150);
                    
                    html += `
                        <div class="search-result-item" style="border-left-color: #ec4899;">
                            <span class="search-result-date" style="background: #fdf2f8; color: #ec4899;">
                                <i class="fas fa-calendar mr-1"></i>${formattedDate}
                            </span>
                            <div class="mt-2">
                                <p class="text-sm text-gray-700 leading-relaxed">${highlightText(context, keyword)}</p>
                            </div>
                        </div>
                    `;
                });
                
                searchResults.innerHTML = html;
            }

            // 显示任务清单模态框
            function showTaskListModal(taskType, filteredTasks) {
                const taskListModalOverlay = document.getElementById('taskListModalOverlay');
                const taskListModalContent = document.getElementById('taskListModalContent');
                const taskListTitle = document.getElementById('taskListTitle');
                const taskListContent = document.getElementById('taskListContent');
                
                // 根据任务类型筛选任务
                const displayTasks = taskType === 'completed' 
                    ? filteredTasks.filter(task => task.completed)
                    : filteredTasks.filter(task => !task.completed);
                
                // 设置标题
                const titleText = taskType === 'completed' ? '已完成任务' : '未完成任务';
                const titleIcon = taskType === 'completed' ? 'fa-check-circle text-blue-500' : 'fa-clock text-green-500';
                taskListTitle.innerHTML = `<i class="fas ${titleIcon} mr-2"></i>${titleText} (${displayTasks.length})`;
                
                // 生成任务列表HTML
                if (displayTasks.length === 0) {
                    taskListContent.innerHTML = `
                        <div class="text-center py-12 text-gray-400">
                            <i class="fas fa-inbox text-5xl mb-3"></i>
                            <p>暂无${titleText}</p>
                        </div>
                    `;
                } else {
                    // 添加任务数量提示
                    let html = `
                        <div class="mb-3 text-sm text-gray-600 flex items-center justify-between">
                            <span>共 <span class="task-count-badge">${displayTasks.length}</span> 个任务</span>
                            ${displayTasks.length > 6 ? '<span class="text-xs text-blue-500"><i class="fas fa-arrow-down mr-1"></i>向下滚动查看更多</span>' : ''}
                        </div>
                    `;
                    
                    // 添加可滚动容器
                    html += '<div class="task-list-container">';
                    html += '<div class="space-y-2">';
                    
                    displayTasks.forEach((task, index) => {
                        const dueDate = new Date(task.dueDate);
                        const formattedDate = `${dueDate.getFullYear()}/${(dueDate.getMonth() + 1).toString().padStart(2, '0')}/${dueDate.getDate().toString().padStart(2, '0')}`;
                        
                        html += `
                            <div class="task-list-item priority-${task.priority}">
                                <div class="flex items-start mb-2">
                                    <i class="fas fa-${task.completed ? 'check-circle text-green-500' : 'circle text-gray-400'} mr-2 mt-1"></i>
                                    <div class="flex-1">
                                        <h4 class="font-medium text-gray-800 ${task.completed ? 'task-completed' : ''}">${task.name}</h4>
                                        ${task.description ? `<p class="text-sm text-gray-600 mt-1 ${task.completed ? 'task-completed' : ''}">${task.description}</p>` : ''}
                                    </div>
                                    <span class="text-xs px-2 py-1 rounded ml-2 ${
                                        task.priority === 'high' ? 'bg-red-100 text-red-600' : 
                                        task.priority === 'medium' ? 'bg-yellow-100 text-yellow-600' : 
                                        'bg-green-100 text-green-600'
                                    }">
                                        ${task.priority === 'high' ? '高' : task.priority === 'medium' ? '中' : '低'}
                                    </span>
                                </div>
                                <div class="flex justify-between items-center text-xs text-gray-500 ml-6">
                                    <span><i class="fas fa-calendar mr-1"></i>截止: ${formattedDate}</span>
                                    ${task.completed ? `<span class="text-green-600"><i class="fas fa-check mr-1"></i>已完成</span>` : ''}
                                </div>
                            </div>
                        `;
                    });
                    
                    html += '</div>'; // 关闭 space-y-2
                    html += '</div>'; // 关闭 task-list-container
                    
                    // 如果任务超过6条，添加底部滚动提示
                    if (displayTasks.length > 6) {
                        html += `
                            <div class="scroll-hint">
                                <i class="fas fa-grip-lines mr-1"></i>
                                已显示全部 ${displayTasks.length} 个任务
                            </div>
                        `;
                    }
                    
                    taskListContent.innerHTML = html;
                }
                
                // 显示模态框
                taskListModalOverlay.style.display = 'block';
                taskListModalContent.style.display = 'block';
                setTimeout(() => {
                    taskListModalOverlay.classList.add('show');
                    taskListModalContent.classList.add('show');
                }, 10);
            }
            
            // 关闭任务清单模态框
            function closeTaskListModal() {
                const taskListModalOverlay = document.getElementById('taskListModalOverlay');
                const taskListModalContent = document.getElementById('taskListModalContent');
                
                taskListModalOverlay.classList.remove('show');
                taskListModalContent.classList.remove('show');
                setTimeout(() => {
                    taskListModalOverlay.style.display = 'none';
                    taskListModalContent.style.display = 'none';
                }, 300);
            }

            // 打开添加任务模态框
            function openModal() {
                modalOverlay.style.display = 'block';
                modalContent.style.display = 'block';
                setTimeout(() => {
                    modalOverlay.classList.add('show');
                    modalContent.classList.add('show');
                }, 10);
            }

            // 关闭模态框
            function closeModal() {
                modalOverlay.classList.remove('show');
                modalContent.classList.remove('show');
                setTimeout(() => {
                    modalOverlay.style.display = 'none';
                }, 300);
            }

            // 添加任务
            function addTask(name, description, dueDate, priority) {
                const newTask = {
                    id: Date.now().toString(),
                    name,
                    description,
                    dueDate,
                    priority,
                    completed: false,
                    createdAt: new Date().toISOString()
                };
                
                tasks.push(newTask);
                saveTasks();
                renderCurrentTab();
            }

            // 切换任务完成状态
            function toggleTaskCompletion(taskId) {
                const taskIndex = tasks.findIndex(task => task.id === taskId);
                if (taskIndex !== -1) {
                    tasks[taskIndex].completed = !tasks[taskIndex].completed;
                    saveTasks();
                    renderCurrentTab();
                }
            }

            // 删除任务
            function deleteTask(taskId) {
                tasks = tasks.filter(task => task.id !== taskId);
                saveTasks();
                renderCurrentTab();
            }

            // 保存任务到本地存储
            function saveTasks() {
                localStorage.setItem('tasks', JSON.stringify(tasks));
            }

            // 表单提交处理
            function handleFormSubmit(e) {
                e.preventDefault();
                
                const name = document.getElementById('taskName').value;
                const description = document.getElementById('taskDescription').value;
                const dueDate = document.getElementById('taskDueDate').value;
                const priority = document.querySelector('input[name="priority"]:checked').value;
                
                addTask(name, description, dueDate, priority);
                taskForm.reset();
                closeModal();
                
                return false;
            }

            // 事件监听器
            tabItems.forEach(item => {
                item.addEventListener('click', function() {
                    tabItems.forEach(i => i.classList.remove('active'));
                    this.classList.add('active');
                    currentTab = this.getAttribute('data-tab');
                    renderCurrentTab();
                });
            });
            
            modalOverlay.addEventListener('click', closeModal);
            taskForm.onsubmit = handleFormSubmit;
            
            // 任务清单模态框关闭事件
            document.getElementById('taskListModalOverlay').addEventListener('click', closeTaskListModal);
            document.getElementById('closeTaskListModal').addEventListener('click', closeTaskListModal);
            
            // 搜索模态框关闭事件
            document.getElementById('searchModalOverlay').addEventListener('click', closeSearchModal);
            document.getElementById('closeSearchModal').addEventListener('click', closeSearchModal);

            // 初始化
            renderCurrentTab();
            
            // 检查自动备份
            checkAutoBackup();
            
            // 初始化云同步
            initCloudSync();
        });

        // ==================== PWA Service Worker 注册 ====================
        
        // 检查浏览器是否支持Service Worker
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                navigator.serviceWorker.register('./service-worker.js')
                    .then(registration => {
                        console.log('✅ Service Worker 注册成功！', registration.scope);
                        
                        // 检查更新
                        registration.addEventListener('updatefound', () => {
                            const newWorker = registration.installing;
                            console.log('🔄 发现新版本...');
                            
                            newWorker.addEventListener('statechange', () => {
                                if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                                    // 新版本可用
                                    if (confirm('📱 发现新版本！\n\n点击"确定"立即更新，点击"取消"下次启动时更新。')) {
                                        newWorker.postMessage({ type: 'SKIP_WAITING' });
                                        window.location.reload();
                                    }
                                }
                            });
                        });
                    })
                    .catch(error => {
                        console.warn('❌ Service Worker 注册失败:', error);
                    });

                // 监听Service Worker控制器变化
                let refreshing = false;
                navigator.serviceWorker.addEventListener('controllerchange', () => {
                    if (!refreshing) {
                        refreshing = true;
                        window.location.reload();
                    }
                });
            });
        }

        // ==================== PWA 安装提示 ====================
        
        let deferredPrompt;
        let installButton = null;

        // 监听安装提示事件
        window.addEventListener('beforeinstallprompt', (e) => {
            console.log('💡 PWA 可以安装');
            
            // 阻止默认的安装提示
            e.preventDefault();
            deferredPrompt = e;
            
            // 显示自定义安装按钮
            showInstallButton();
        });

        // 显示安装按钮
        function showInstallButton() {
            // 检查是否已经安装
            if (window.matchMedia('(display-mode: standalone)').matches) {
                console.log('✅ 应用已安装');
                return;
            }

            // 创建安装提示横幅
            const installBanner = document.createElement('div');
            installBanner.id = 'installBanner';
            installBanner.style.cssText = `
                position: fixed;
                bottom: 70px;
                left: 10px;
                right: 10px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 12px 16px;
                border-radius: 12px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
                z-index: 1000;
                display: flex;
                align-items: center;
                justify-content: space-between;
                animation: slideUp 0.3s ease;
            `;
            
            installBanner.innerHTML = `
                <div style="flex: 1;">
                    <div style="font-weight: 600; margin-bottom: 4px; font-size: 14px;">📱 安装应用到主屏幕</div>
                    <div style="font-size: 12px; opacity: 0.9;">像原生APP一样使用，支持离线访问</div>
                </div>
                <div style="display: flex; gap: 8px;">
                    <button id="installBtn" style="background: white; color: #667eea; padding: 8px 16px; border-radius: 8px; border: none; font-weight: 600; font-size: 13px; cursor: pointer;">
                        安装
                    </button>
                    <button id="dismissBtn" style="background: rgba(255,255,255,0.2); color: white; padding: 8px 12px; border-radius: 8px; border: none; font-size: 13px; cursor: pointer;">
                        ✕
                    </button>
                </div>
            `;
            
            // 添加动画样式
            const style = document.createElement('style');
            style.textContent = `
                @keyframes slideUp {
                    from {
                        transform: translateY(100%);
                        opacity: 0;
                    }
                    to {
                        transform: translateY(0);
                        opacity: 1;
                    }
                }
            `;
            document.head.appendChild(style);
            
            document.body.appendChild(installBanner);
            
            // 安装按钮事件
            document.getElementById('installBtn').addEventListener('click', async () => {
                if (!deferredPrompt) return;
                
                // 显示安装提示
                deferredPrompt.prompt();
                
                // 等待用户响应
                const { outcome } = await deferredPrompt.userChoice;
                console.log(`用户选择: ${outcome}`);
                
                if (outcome === 'accepted') {
                    console.log('✅ 用户接受安装');
                } else {
                    console.log('❌ 用户拒绝安装');
                }
                
                // 清除提示
                deferredPrompt = null;
                installBanner.remove();
            });
            
            // 关闭按钮事件
            document.getElementById('dismissBtn').addEventListener('click', () => {
                installBanner.remove();
                // 7天后再次提示
                localStorage.setItem('installDismissed', Date.now() + 7 * 24 * 60 * 60 * 1000);
            });
            
            // 检查是否在冷却期
            const dismissedUntil = localStorage.getItem('installDismissed');
            if (dismissedUntil && Date.now() < parseInt(dismissedUntil)) {
                installBanner.remove();
            }
        }

        // 监听应用安装成功事件
        window.addEventListener('appinstalled', () => {
            console.log('🎉 应用安装成功！');
            deferredPrompt = null;
            
            // 移除安装横幅
            const banner = document.getElementById('installBanner');
            if (banner) banner.remove();
            
            // 显示欢迎消息
            setTimeout(() => {
                alert('🎉 安装成功！\n\n现在可以从主屏幕快速打开TodoList了！');
            }, 500);
        });

        // 检测是否在独立模式下运行（已安装）
        if (window.matchMedia('(display-mode: standalone)').matches) {
            console.log('✅ 应用以独立模式运行（已安装）');
        }

        // iOS Safari添加到主屏幕提示
        if (navigator.standalone === false) {
            // 用户使用iOS Safari但未安装
            console.log('💡 iOS用户可以通过"分享" → "添加到主屏幕"来安装应用');
        } else if (navigator.standalone === true) {
            // 应用已安装并在独立模式运行
            console.log('✅ iOS应用已安装');
        }

        // ==================== Firebase 云端同步功能 ====================
        
        // Firebase配置和状态
        let firebaseApp = null;
        let firebaseAuth = null;
        let firebaseDb = null;
        let currentUser = null;
        let syncEnabled = false;

        // 初始化云同步
        function initCloudSync() {
            // 检查是否有保存的Firebase配置
            const savedConfig = localStorage.getItem('firebaseConfig');
            
            if (savedConfig) {
                try {
                    const config = JSON.parse(savedConfig);
                    loadFirebaseAndInit(config);
                } catch (error) {
                    console.error('Firebase配置加载失败:', error);
                }
            }
            
            // 绑定设置按钮事件
            setupCloudSyncUI();
        }

        // 设置云同步UI事件
        function setupCloudSyncUI() {
            // 配置按钮
            document.addEventListener('click', (e) => {
                if (e.target && e.target.id === 'setupCloudSyncBtn') {
                    showFirebaseSetup();
                }
            });
            
            // 保存配置按钮
            document.getElementById('saveFirebaseConfig').addEventListener('click', saveFirebaseConfig);
            
            // 取消按钮
            document.getElementById('cancelFirebaseSetup').addEventListener('click', () => {
                document.getElementById('firebaseSetupModal').style.display = 'none';
            });
        }

        // 显示Firebase设置对话框
        function showFirebaseSetup() {
            const modal = document.getElementById('firebaseSetupModal');
            const input = document.getElementById('firebaseConfigInput');
            
            // 如果已有配置，显示当前配置
            const savedConfig = localStorage.getItem('firebaseConfig');
            if (savedConfig) {
                input.value = JSON.stringify(JSON.parse(savedConfig), null, 2);
            }
            
            modal.style.display = 'flex';
        }

        // 保存Firebase配置
        function saveFirebaseConfig() {
            const input = document.getElementById('firebaseConfigInput').value.trim();
            
            if (!input) {
                alert('❌ 请输入Firebase配置');
                return;
            }
            
            try {
                const config = JSON.parse(input);
                
                // 验证配置必需字段
                if (!config.apiKey || !config.authDomain || !config.projectId) {
                    throw new Error('配置缺少必需字段');
                }
                
                // 保存配置
                localStorage.setItem('firebaseConfig', JSON.stringify(config));
                
                // 关闭对话框
                document.getElementById('firebaseSetupModal').style.display = 'none';
                
                // 加载Firebase并初始化
                loadFirebaseAndInit(config);
                
                alert('✅ Firebase配置保存成功！\n\n页面将刷新以启用云同步功能。');
                setTimeout(() => location.reload(), 1000);
                
            } catch (error) {
                alert('❌ 配置格式错误：' + error.message + '\n\n请确保输入的是有效的JSON格式。');
            }
        }

        // 动态加载Firebase SDK并初始化
        function loadFirebaseAndInit(config) {
            // 提示用户：由于Firebase SDK较大，需要动态加载
            console.log('📦 正在加载Firebase SDK...');
            
            showSyncStatus('正在加载Firebase...', 'syncing');
            
            // 动态加载Firebase SDK
            const script1 = document.createElement('script');
            script1.src = 'https://www.gstatic.com/firebasejs/10.7.1/firebase-app-compat.js';
            script1.onload = () => {
                const script2 = document.createElement('script');
                script2.src = 'https://www.gstatic.com/firebasejs/10.7.1/firebase-auth-compat.js';
                script2.onload = () => {
                    const script3 = document.createElement('script');
                    script3.src = 'https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore-compat.js';
                    script3.onload = () => {
                        initializeFirebase(config);
                    };
                    document.head.appendChild(script3);
                };
                document.head.appendChild(script2);
            };
            document.head.appendChild(script1);
        }

        // 初始化Firebase
        function initializeFirebase(config) {
            try {
                // 初始化Firebase
                firebaseApp = firebase.initializeApp(config);
                firebaseAuth = firebase.auth();
                firebaseDb = firebase.firestore();
                
                console.log('✅ Firebase初始化成功');
                
                // 监听认证状态
                firebaseAuth.onAuthStateChanged((user) => {
                    if (user) {
                        currentUser = user;
                        syncEnabled = true;
                        console.log('✅ 用户已登录:', user.email || '匿名用户');
                        updateCloudSyncStatus('已登录: ' + (user.email || '匿名用户'));
                        
                        // 启动自动同步
                        startAutoSync();
                    } else {
                        currentUser = null;
                        syncEnabled = false;
                        updateCloudSyncStatus('未登录 - 点击登录');
                        
                        // 提示登录
                        setTimeout(() => {
                            if (confirm('☁️ Firebase配置成功！\n\n是否现在登录Google账号以启用云同步？')) {
                                signInWithGoogle();
                            }
                        }, 500);
                    }
                });
                
            } catch (error) {
                console.error('❌ Firebase初始化失败:', error);
                showSyncStatus('配置失败', 'error');
                alert('❌ Firebase初始化失败：' + error.message);
            }
        }

        // Google登录
        function signInWithGoogle() {
            const provider = new firebase.auth.GoogleAuthProvider();
            firebaseAuth.signInWithPopup(provider)
                .then((result) => {
                    console.log('✅ 登录成功');
                    alert('🎉 登录成功！\n\n云同步已启用，数据将自动同步到所有设备。');
                })
                .catch((error) => {
                    console.error('登录失败:', error);
                    alert('❌ 登录失败：' + error.message);
                });
        }

        // 启动自动同步
        function startAutoSync() {
            if (!syncEnabled || !currentUser) return;
            
            // 监听本地数据变化
            let syncTimer = null;
            const originalSetItem = localStorage.setItem.bind(localStorage);
            
            localStorage.setItem = function(key, value) {
                originalSetItem(key, value);
                
                // 如果是任务或日记数据，触发同步
                if (key === 'tasks' || key === 'dailyNotes') {
                    clearTimeout(syncTimer);
                    syncTimer = setTimeout(() => {
                        syncToCloud();
                    }, 2000); // 2秒延迟，避免频繁同步
                }
            };
            
            // 首次同步
            syncFromCloud();
        }

        // 同步到云端
        function syncToCloud() {
            if (!syncEnabled || !currentUser) return;
            
            showSyncStatus('同步中...', 'syncing');
            
            const data = {
                tasks: JSON.parse(localStorage.getItem('tasks') || '[]'),
                dailyNotes: JSON.parse(localStorage.getItem('dailyNotes') || '{}'),
                lastSync: firebase.firestore.FieldValue.serverTimestamp()
            };
            
            firebaseDb.collection('users').doc(currentUser.uid).collection('data').doc('todolist')
                .set(data, { merge: true })
                .then(() => {
                    console.log('✅ 数据已同步到云端');
                    showSyncStatus('已同步', 'synced');
                    setTimeout(() => hideSyncStatus(), 2000);
                })
                .catch((error) => {
                    console.error('❌ 同步失败:', error);
                    showSyncStatus('同步失败', 'error');
                    setTimeout(() => hideSyncStatus(), 3000);
                });
        }

        // 从云端同步
        function syncFromCloud() {
            if (!syncEnabled || !currentUser) return;
            
            showSyncStatus('正在同步...', 'syncing');
            
            firebaseDb.collection('users').doc(currentUser.uid).collection('data').doc('todolist')
                .get()
                .then((doc) => {
                    if (doc.exists) {
                        const cloudData = doc.data();
                        
                        // 合并数据（云端优先）
                        if (cloudData.tasks) {
                            localStorage.setItem('tasks', JSON.stringify(cloudData.tasks));
                        }
                        if (cloudData.dailyNotes) {
                            localStorage.setItem('dailyNotes', JSON.stringify(cloudData.dailyNotes));
                        }
                        
                        console.log('✅ 数据已从云端同步');
                        showSyncStatus('同步完成', 'synced');
                        
                        // 刷新界面
                        setTimeout(() => {
                            location.reload();
                        }, 1000);
                    } else {
                        console.log('📝 云端暂无数据，将上传本地数据');
                        syncToCloud();
                    }
                })
                .catch((error) => {
                    console.error('❌ 从云端同步失败:', error);
                    showSyncStatus('同步失败', 'error');
                });
        }

        // 显示同步状态
        function showSyncStatus(message, type) {
            const status = document.getElementById('syncStatus');
            const text = document.getElementById('syncStatusText');
            
            text.textContent = message;
            status.className = 'sync-status show ' + type;
        }

        // 隐藏同步状态
        function hideSyncStatus() {
            const status = document.getElementById('syncStatus');
            status.classList.remove('show');
        }

        // 更新云同步卡片状态
        function updateCloudSyncStatus(status) {
            const statusElement = document.getElementById('cloudSyncStatus');
            if (statusElement) {
                statusElement.textContent = status;
            }
            
            const button = document.getElementById('setupCloudSyncBtn');
            if (button && currentUser) {
                button.innerHTML = '<i class="fas fa-sign-out-alt mr-2"></i>退出登录';
                button.onclick = () => {
                    if (confirm('确定要退出登录吗？\n\n退出后云同步将停止，但本地数据不会删除。')) {
                        firebaseAuth.signOut().then(() => {
                            alert('✅ 已退出登录');
                            location.reload();
                        });
                    }
                };
            }
        }
    </script>
</body>
</html>